<template>
  <el-dialog :model-value="visible" width="40%" title="分配权限" @close="close">
    <el-tree :data="rightsList" ref="treeRef" show-checkbox node-key="id" default-expand-all
      :default-checked-keys="userRightsList.arr" :props="defaultProps" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, getCurrentInstance } from 'vue';
import { getRightsListApi, setRolesRightsApi } from '@/api/authInterface';

const { proxy } = getCurrentInstance() as any

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => { }
  }
})
const emits = defineEmits(['close'])

const defaultProps = {
  children: 'children',
  label: 'authName',
}

const rightsList = ref()
const userRightsList = reactive<{arr: number[]}>({
  arr: []
})
watch(() => props.visible, (newValue) => {
  if (newValue) {
    getRightsListApi('tree').then(res => {
      rightsList.value = res.data
      ergodicRights(props.rowData.children)
      console.log(userRightsList.arr);
      
    })
  }
})

const ergodicRights = (arr: any) => {
  arr.forEach((item: any) => {
    if (item.children) {
      ergodicRights(item.children)
    } else {
      userRightsList.arr.push(item.id)
    }
  })
}

const treeRef = ref()
const submit = () => {
  const selectedNodeId = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys()
  ]
  const nodeIdStr = selectedNodeId.join(',')

  setRolesRightsApi(props.rowData.id, { rids: nodeIdStr }).then(res => {
    close()
    proxy.$message.success('更新成功')
  })
}

const close = () => {
  userRightsList.arr = []
  emits('close')
}
</script>

<style scoped></style>